/**
 * 使用VueUse的useDark进行深色主题切换
 */

import { useDark, useToggle } from '@vueuse/core'

// 创建link元素,引入dark.less
const createDarkStyleElement = () => {
  const newDarkTheme = document.createElement('link')
  newDarkTheme.setAttribute('rel', 'stylesheet')
  newDarkTheme.setAttribute('href', '/src/style/dark.less')
  newDarkTheme.setAttribute('id', 'dark-theme-style')
  const docHead = document.querySelector('head')
  docHead?.append(newDarkTheme)
}
// 移除link元素
const removeDarkStyleElement = (element: HTMLElement) => {
  const parentNode = element.parentNode
  parentNode?.removeChild(element)
}
// 切换深色主题
const toggleTheme = (isDark = true) => {
  const darkStyleElement = document.querySelector('#dark-theme-style')
  if (isDark) {
    // 如果#dark-theme-style不存在,则创建
    if (darkStyleElement == null) {
      createDarkStyleElement()
    }
    // 给element plus加上dark类
    const HTMLElement = document.documentElement
    HTMLElement.classList.add('dark')
  } else {
    // 如果#dark-theme-style存在,则移除
    if (darkStyleElement != null) {
      removeDarkStyleElement(darkStyleElement as HTMLElement)
    }
    // 给element plus移除dark类
    const HTMLElement = document.documentElement
    HTMLElement.classList.remove('dark')
  }
}

// VueUse
export const isDark = useDark({
  onChanged(isDark) {
    toggleTheme(isDark)
  }
})
export const toggleDark = useToggle(isDark)
